<?php
namespace app\user\controller;

use app\common\controller\Frontend;
use think\Controller;
use think\Config;
use think\Validate;
use think\captcha\Captcha;
use think\Session;
use think\Db;
use app\common\model\User;
class Register extends Controller
{
    public function _initialize()
    {
        parent::_initialize();
        
        $adminhost =Db::name('Config')->where('name','memberHost')->value('value');
        if(!empty($adminhost)){
            $host = $this->request->host(true);
            if($host !== $adminhost){
                die('访问限制');
            }
        }
    }
    public function index(){
        if($this->request->isPost()){
            $data = $this->request->post('',[],'strip_tags');
            $rule = [
                'username'  => 'require|length:3,30',
                'password'  => 'require|length:3,30',
                'captcha' => 'require|captcha',
            ];
            $validate = new Validate($rule, [], ['username' => '账户', 'password' => '密码', 'captcha' => '验证码']);
            $result = $validate->check($data);
            if (!$result) {
                $this->error($validate->getError());
            }
            $user = User::get(['username' => $data['username']]);
            if (!!$user) {
                $this->error('账号已存在');

            }
            $data['password'] = md5(md5($data['password']) . Config::get('auth_key'));
            $result = model('User')->autoField(true)->save($data);
            if ($result === true) {
                $this->success('登录成功');
            } else {
                $msg =  '注册失败';
                $this->error($msg);
            }
        }

        return $this->fetch();
    }
}